package autosession

import (
	"context"
	"net/http"
)

type HeaderInspector struct {
	encryptor InspectorEncryptor
}

func NewHeaderInspector() Inspector {
	return NewHeaderInspectorWith(&JwtEncryptor{})
}

func NewHeaderInspectorWith(enc InspectorEncryptor) Inspector {
	return HeaderInspector{
		encryptor: enc,
	}
}

func (i HeaderInspector) SignId(ctx context.Context, sessionId string, options *Options) (string, error) {
	return i.encryptor.Sign(sessionId, options)
}

func (i HeaderInspector) Read(ctx context.Context, req *http.Request, name string) (sessionId string, err error) {
	jwtStr := req.Header.Get(name)
	if jwtStr != "" {
		return i.encryptor.Parse(jwtStr)
	}
	return "", &NotFoundError{"请求header中未读取到" + name}
}

func (i HeaderInspector) Write(ctx context.Context, name, sessionId string, options *Options, writter WritterFunc) (string, error) {
	signedString, err := i.encryptor.Sign(sessionId, options)
	if err != nil {
		return "", err
	}
	err = writter(ctx, name, signedString)
	if err != nil {
		return "", err
	}
	return signedString, nil
}
